'use strict';

const Controller = require('egg').Controller;

const jwt = require('jsonwebtoken');

class UserController extends Controller {
    async registry() {
        let {ctx,service} = this;

        let {phone,password,role} = ctx.request.body;

        if(/\d{11}$/.test(phone) && password && role){
            //1.排重
            let user = await service.user.selectUser(phone);
            if(user.length){
                ctx.body = {
                    code:3,
                    msg:'此用户已存在'
                }
            }else{
                try{
                    let hmcPwd = ctx.helper.hmc(password);
                    await service.user.registry(phone,hmcPwd,role);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:e
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    async login(){
        let {ctx,service} = this;

        let {phone,password} = ctx.request.body;

        if(/\d{11}$/.test(phone) && password){
            let hmcPwd = ctx.helper.hmc(password);
            let user = await service.user.login(phone,hmcPwd);
            if(user.length){
                let {role} = user[0];
                let token = jwt.sign({role},'yuekao',{expiresIn:60*60});
                ctx.body = {
                    code:1,
                    msg:'登录成功',
                    token
                }
            }else{
                ctx.body = {
                    code:0,
                    msg:'登录失败'
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
